#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-06-12 17:35:58
# @Author  : yangchaojun (YYChildren@gmail.com)
# @Link    : https://git.mingchao.com/yangchaojun
# @Version : 1.0.0

import pymysql
from .config import CONFIG

def get_db_conn():
    mysql_conf = dict(
        host = CONFIG['mysql:host'],
        port = int(CONFIG['mysql:port']),
        user = CONFIG['mysql:user'],
        password = CONFIG['mysql:password'],
        charset = CONFIG['mysql:charset']
    )
    conn = pymysql.connect(**mysql_conf)
    return conn

def get_record_from_sql(sql):
    conn = get_db_conn()
    cursor = conn.cursor()
    cursor.execute(sql)
    fields = [i[0] for i in cursor.description]
    rs = [dict(zip(fields, i)) for i in cursor.fetchall()]
    cursor.close()
    conn.close()
    return rs

def get_record(database, table, fields, limit, offset):
    fs = ",".join(fields)
    sql = "SELECT %s FROM %s.%s limit %s offset %s" % (fs, database, table, limit, offset)
    return get_record_from_sql(sql)